package com.dz.client.controller;

import com.dz.server.pojo.User;
import com.dz.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class PersonalController {
    @Autowired
    private UserService userService;
    //去个人中心页面
    @RequestMapping("/toPersonal")
    public String toPersonal(HttpSession session,Model model){
        String username =(String)session.getAttribute("username");
        User user = userService.selectUserByName(username);
        model.addAttribute("user",user);
        return "client/personal";
    }
    //用户注册（添加一个用户)
    @RequestMapping("/register")
    public String Register(User user, String repassword, Model model){
        //注册是否成功
        boolean isSuccess = userService.registerUser(user, repassword);
        if (isSuccess){
            model.addAttribute("msg","注册成功");
        }
        else
            model.addAttribute("msg","注册失败，请更换用户名或检查密码是否输入正确");
        return "common/login";
    }
    //去修改页面
    @RequestMapping("/toUpdateUser{id}")
    public String toUpdateUser(@PathVariable("id")int id, Model model){
        User user = userService.getById(id);
        model.addAttribute("user",user);
        return "client/updateUser";
    }
    //修改用户信息(用户名必须要修改)
    @RequestMapping("/updateUser")
    public String updateUser(User user, String repassword, Model model, HttpSession session){
        boolean isSuccess = userService.updateUser(user, repassword);
        if (isSuccess){
            model.addAttribute("msg","修改成功");
            session.setAttribute("username",user.getUsername());
        }
        else
            model.addAttribute("msg","修改失败，请更换用户名或检查密码是否输入正确");
        return "client/updateUser";
    }
    //退出登录
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("username");
        return "common/login";
    }
}
